package com.baijiaoxi.common.model.base.service.base;

import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;
import com.baijiaoxi.common.model.base.mapper.CoreMapper;
import com.baijiaoxi.common.model.base.model.CoreModel;
import com.baijiaoxi.common.model.base.service.interceptor.BaseInterceptor;
import com.baijiaoxi.common.model.base.service.interceptor.SaveInterceptor;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;


public interface SaveService<E extends CoreModel> extends BaseService<E>, SaveInterceptor<E>, BaseInterceptor<E> {

    /**
     * 自动判断要保存的数据是更新还是插入
     *
     * @param entity
     * @return
     */
    default boolean isInsert(E entity) {
        if (entity.getId() == null)
            return true;
        else
            return getMapper().selectById(entity.getIdAsSerializable()) == null;
    }


    /**
     * 新增/更新
     * 依据ID是否为null判断
     */
    default E autoSave(E entity) {
        if (entity == null)
            throw CoreException.create(CommonError.objectIsNull);
        beforeAutoSave(entity);
        beforeSave(entity);
        CoreMapper<E> mapper = getMapper();
        if (isInsert(entity)) {
            beforeInsert(entity);
            mapper.insert(entity);
            afterInsert(entity);
            afterChange(ChangeType.insert, entity);
        } else {
            beforeUpdate(entity);
            mapper.updateById(entity);
            afterUpdate(entity);
            afterChange(ChangeType.updateById, entity);
        }
        afterAutoSave(entity);
        afterSave(entity);

        return entity;

    }

    /**
     * 新增/更新
     * 依据ID是否为null判断
     */
    default E updateById(E entity) {
        if (entity == null)
            throw CoreException.create(CommonError.objectIsNull);
        CoreMapper<E> mapper = getMapper();
        beforeAutoSave(entity);
        beforeSave(entity);
        beforeUpdate(entity);
        mapper.updateById(entity);
        afterUpdate(entity);
        afterAutoSave(entity);
        afterSave(entity);
        afterChange(ChangeType.updateById, entity);
        return entity;
    }

    default boolean update(E entity, Wrapper<E> updateWrapper) {
        return SqlHelper.retBool(getMapper().update(entity, updateWrapper));
    }

    /**
     * 新增/更新
     * 依据ID是否为null判断
     */
    default E insert(E entity) {
        if (entity == null)
            throw CoreException.create(CommonError.objectIsNull);
        beforeAutoSave(entity);
        beforeSave(entity);
        CoreMapper<E> mapper = getMapper();
        beforeInsert(entity);
        mapper.insert(entity);
        afterInsert(entity);
        afterAutoSave(entity);
        afterSave(entity);
        afterChange(ChangeType.insert, entity);
        return entity;
    }
}
